function flatten(root: TreeNode | null): void {
    if (!root) return;

    if (root.left) {
        let left = root.left;
        let cur = root.left;
        while (cur.right) {
            cur = cur.right;
        }
        cur.right = root.right;
        root.right = left;
        root.left = null;
    }
    flatten(root.right);
};

class TreeNode {
    val: number
    left: TreeNode | null
    right: TreeNode | null
    constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
        this.val = (val===undefined ? 0 : val)
        this.left = (left===undefined ? null : left)
        this.right = (right===undefined ? null : right)
    }
}